package com.aft.terra.modules.game.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.aft.terra.modules.game.model.base.BaseGameDetails;
import com.jfinal.plugin.activerecord.Db;

public class GameDetails extends BaseGameDetails<GameDetails> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static final GameDetails dao = new GameDetails();

	public Integer queryCount(String userId) {
		String sql ="select count(*) from t_game_details where user_id = ?";
		return Db.queryLong(sql, userId).intValue();
	}
	public Integer queryCount() {
		String sql ="select count(*) from t_game_details";
		return Db.queryLong(sql).intValue();
	}
	
	public GameDetails queryDateScore(String startDate,String endDate,long userId){
		StringBuilder sql = new StringBuilder();
		sql.append("select SUM(score) scoreSum from t_game_details where 1 = 1 ");
		sql.append(" and user_id = ? ");
		if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)){
			sql.append(" and modifyDate BETWEEN '");
			sql.append(startDate);
			sql.append(" 00:00:00' and '");
			sql.append(endDate);
			sql.append(" 23:59:59'");
		}
		sql.append(" GROUP BY user_id ");
		return findFirst(sql.toString(),userId);
	}
	
	public GameDetails findByUserId(String userId){
		String sql ="select *,min(createDate) from t_game_details where user_id = ? ";
		return findFirst(sql,userId);
	}
	
	public Boolean updateById(Integer pId,Integer probabilityValue,Integer userId) {
		String sql ="update d_game_details set score = ?,modifyDate = ?,is_end = 1  where id = ? and user_id = ? and is_end = 0";
		return Db.update(sql,probabilityValue,new Date(),pId,userId) > 0 ? true : false;
	}

	public List<GameDetails> queryUserToDateGameDetails(Boolean startOnEndDate , String startDate, String endDate,Integer limitCount) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT user_id,user_name,user_headimgurl,SUM(score) scoreSum ")
			.append("FROM d_game_details WHERE is_end = 1");
		List<String> param = new ArrayList<String>();
		if(!startOnEndDate){
			if(StringUtils.isNotBlank(startDate) &&StringUtils.isNotBlank(endDate) ){
				sql.append(" and modifyDate BETWEEN '");
				sql.append(startDate);
				sql.append(" 00:00:00' and '");
				sql.append(endDate);
				sql.append(" 23:59:59'");
			}
		}
		sql.append("  GROUP BY user_id   ORDER BY scoreSum desc,modifyDate asc LIMIT ")
			.append(limitCount);
		return find(sql.toString(),param.toArray());
	}
}
